#include <netinet/in.h>		/* sockaddr_in */
#include <sys/socket.h>		/* socket(), connect() */
#include <sys/types.h>		/* see man 2 socket */
#include <strings.h>		/* bzero() */
#include <arpa/inet.h>		/* htons() */
#include <unistd.h>			/* read() */
#include <stdio.h>			/* fputs(), stdout */
#include <stdlib.h>			/* exit() */

#define	MAXLINE		4096	/* max text line length */

int
main(int argc, char *argv[])
{
	int 				sockfd, n;
	char				recvline[MAXLINE + 1];
	struct sockaddr_in 	servaddr;	

	if (argc != 2) {
		printf("usage: %s <IP address>\n", argv[0]);
		exit(1);
	}

	/* init client socket */
	if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ) {
		printf("socket() error!\n");
		exit(1);
	}

	/* init server address */
	bzero(&servaddr, sizeof(servaddr));		/* see UNP p8 */
	servaddr.sin_family = AF_INET;
	servaddr.sin_port	= htons(13);
	if ( (inet_pton(AF_INET, argv[1], &servaddr.sin_addr)) == -1 ) {
		printf("inet_pton() error!\n");
		exit(1);
	}

	/* connnect server by servaddr */
	if ( (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr))) == -1 ) {
		printf("connect() error!\n");
		exit(1);
	}

	/* read and display server's reply */
	while( (n = read(sockfd, recvline, MAXLINE)) > 0 ) {
		//recvline[n] = 0;		/* I don't understand */	
		if ( fputs(recvline, stdout) == EOF ) {
			printf("fputs() error!\n");
			exit(1);
		}
	}
	if (n < 0) {
		printf("read() error!\n");
		exit(1);
	}

	exit(0);
}
